package com.junbao.message.ui.web;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;
import com.junbao.commom.exception.JunBaoException;
import com.junbao.commom.util.JsonUtils;
import com.junbao.message.infrastructure.result.Result;

public class BaseServlet extends HttpServlet{

	
	private static final long serialVersionUID = -3413044011868280136L;
	
	private static final Logger LOGGER = LoggerFactory.getLogger(BaseServlet.class);
	
	/**
	 * 参数返回
	 * @param response
	 * @param resultData
	 */
	protected void writer(HttpServletResponse response,Result resultData){
		try {
			LOGGER.info("返回数据: "+ JSONObject.toJSONString(resultData.buildResultMsg()));
			PrintWriter writer = response.getWriter();
			writer.print(resultData.buildResultMsg());
			return;
		} catch (IOException e) {
			LOGGER.error("数据返回异常！",e);
		}
	}
	
	/**
	 * 获取请求数据
	 * @param request
	 * @param response
	 * @return
	 * @throws JunBaoException
	 * @throws Exception
	 */
	protected String getRequestData(HttpServletRequest request,HttpServletResponse response) throws JunBaoException,Exception{
		BufferedReader br = null;
		StringBuilder sb = new StringBuilder();
		try {
			br = new BufferedReader(new InputStreamReader(request.getInputStream(), "UTF-8"));
			String line = null;
			while ((line = br.readLine()) != null) {
				sb.append(line);
			}
			if (StringUtils.isEmpty(sb)) {
				throw new JunBaoException(Result.REQUEST_DATA_NULL.getResult_code(), Result.REQUEST_DATA_NULL.getResult_msg());
			}
		} catch (Exception e) {
			throw new Exception("读取请求参数异常！",e);
		}
		return sb.toString();
	}
	
	/**
	 * 参数检查
	 * @param requestData 请求参数
	 * @param params 被检查参数
	 * @throws JunBaoException
	 */
	protected void requestParmCheck(String requestData,String... params) throws JunBaoException{
		net.sf.json.JSONObject source = net.sf.json.JSONObject.fromObject(requestData);
		JsonUtils.containsKeysAndKeyValueIsEmpty(source, params);
	}
}
